﻿using Client;
using Seagull.BarTender.Print;
using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tools
{
    public partial class FormYcdMac : Form
    {
        private  readonly string BASE_PATH = AppDomain.CurrentDomain.SetupInformation.ApplicationBase+"MacDirectory\\";

        private string _printerName = "";
        private string _btwPath = "";
        private string _objName = "";

        public FormYcdMac()
        {
            InitializeComponent();
        }

        private void buttonCreate_Click(object sender, EventArgs e)
        {
            try
            {
                //判断选择的PONTYPE是EPON还是GPON，还是没有选择
                string ponType = this.comboBoxBosaType.Text;
                int macNum = int.Parse(this.textBoxMacNum.Text.Trim());

                //判断数量是否大于0，小于5000
                if(ponType!="EPON" && ponType != "STIA")
                {
                    MessageBox.Show("请选择BOSA类型");
                    return;
                }
            
                if(macNum<=0 || macNum > 5000)
                {
                    MessageBox.Show("只能生成小于5000个MAC地址");
                    return;
                }

                this.richTextBoxMsg.Clear();
                this.textBoxMacNum.Clear();

                this.labelTotal.Text = macNum.ToString();

                CreateMac(ponType, macNum);//生成MAC地址
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void SetControlText(Control con,string text)
        {
            if (this.InvokeRequired)
            {
                Action<Control, string> d = new Action<Control, string>(SetControlText);
                Invoke(d, con, text);
            }
            else
            {
                con.Text = text;
            }
        }

        private void CreateMac(string ponType, int macNum)
        {
            Task.Factory.StartNew(()=>
            {
                long firstMacX = 0;//第一个MAC地址的16进制数

                List<Device_Data> listDevice = new List<Device_Data>();

                //查到最大ID的ponTYPE类型的PRODUCT YCD_MAC和DEVICE_DATA_ID
                YCD_DEVICE ycdW = new YCD_DEVICE();
                ycdW.SetWhere(string.Format("ID = (select top 1 ID from YCD_DEVICE where PON_TYPE='{0}' order by ID desc)", ponType));
                var selectYcd = MethodWcf.SelectYcdDeviceClient(ycdW);
                //MessageBox.Show(selectProduct.message);

                string sqlDeviceWhere = null;//查询DEVICE的语句

                if (selectYcd.result == false)
                {
                    if (ponType == "EPON")
                    {
                        firstMacX = SharedData.FIRST_EPON_MAC;
                    }
                    else
                    {
                        firstMacX = SharedData.FIRST_GPON_MAC;
                    }
                    //找开头的device数据
                    sqlDeviceWhere = string.Format("ID IN (SELECT TOP {0} ID FROM Device_Data WHERE PONType='{1}')", macNum, ponType);
                }
                else
                {
                    firstMacX = Convert.ToInt64(selectYcd.value[0].YCD_MAC, 16)+1;
                    //找大于ID的devicedata数据
                    sqlDeviceWhere = string.Format("ID IN (SELECT TOP {0} ID FROM Device_Data WHERE PONType='{1}'  AND ID>{2})", macNum, ponType,selectYcd.value[0].DEVICE_DATA_ID);
                }

                //查找对应的Device_ID

                Device_Data deviceW = new Device_Data();
                deviceW.SetWhere(sqlDeviceWhere);

                var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);

                if (selectDevice.result)//给listDevice赋值
                {
                    listDevice = selectDevice.value;
                }

                if (listDevice == null)
                {
                    //找开头的device数据
                    sqlDeviceWhere = string.Format("ID IN (SELECT TOP {0} ID FROM Device_Data WHERE PONType='{1}')", macNum, ponType);

                    deviceW.SetWhere(sqlDeviceWhere);

                    selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
                    listDevice = selectDevice.value;
                }
                else if (listDevice.Count < macNum)
                {
                    //找开头的device数据
                    sqlDeviceWhere = string.Format("ID IN (SELECT TOP {0} ID FROM Device_Data WHERE PONType='{1}')", macNum - listDevice.Count, ponType);
                    deviceW.SetWhere(sqlDeviceWhere);

                    selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
                    listDevice.AddRange(selectDevice.value);
                }

                if(listDevice==null || listDevice.Count != macNum)
                {
                    MessageBox.Show("未能找到足够的DEVICE_DATA数据");
                    return;
                }

                YCD_DEVICE ycdDevice = new YCD_DEVICE();

                if (Directory.Exists(BASE_PATH) == false)
                {
                    Directory.CreateDirectory(BASE_PATH);
                }

                string fileName = string.Format("{0}{1}_YCD_MAC.txt",BASE_PATH, DateTime.Now.ToString("yyyyMMddHHmmss"));

                StreamWriter fileWrite = new StreamWriter(fileName, true);

                //写入对应的数据到数据库中
                for (int i = 0; i < listDevice.Count; i++)
                {
                    ycdDevice.Clear();
                    ycdDevice.SetUpdate();

                    ycdDevice.YCD_MAC = (firstMacX + i).ToString("X");
                    ycdDevice.DEVICE_DATA_ID = listDevice[i].ID;
                    ycdDevice.PON_TYPE = ponType;

                    var insertPro = MethodWcf.InsertYcdDeviceClient(ycdDevice);

                    fileWrite.WriteLine(ycdDevice.YCD_MAC);

                    SetControlText(labelMore, (i+1).ToString());

                    if (this.checkBoxAutoPrint.Checked)
                        PrintLabel(ycdDevice.YCD_MAC, _btwPath,_objName, _printerName);

                    AppendText(this.richTextBoxMsg,ycdDevice.YCD_MAC);
                }

                fileWrite.Close();
            });
        }


        private void AppendText(RichTextBox rich,string msg)
        {
            if (this.InvokeRequired)
            {
                Action<RichTextBox, string> d = new Action<RichTextBox, string>(AppendText);
                Invoke(d, rich, msg);
            }
            else
            {
                if (string.IsNullOrEmpty(msg)==false)
                {
                    rich.AppendText(msg);
                    rich.AppendText("\r\n");
                }
            }
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }

        #region 标签打印代码
        //打印标签
        private void PrintLabel(string mac, string btwPath, string btwQuery, string printer)
        {
            //Task.Factory.StartNew(()=>
            //{
            if (string.IsNullOrEmpty(btwPath) || File.Exists(btwPath) == false)
            {
                MessageBox.Show("未能获得打标文件，打印失败！请打开打标软件手动打印！");
                return;
            }


            if (string.IsNullOrEmpty(mac) || string.IsNullOrEmpty(btwQuery))
            {
                MessageBox.Show("MAC或查询代码为空，打印失败");
                return;
            }

            Engine bt = new Engine();

            bt.Start();
            LabelFormatDocument btFormat = bt.Documents.Open(btwPath);
            //btFormat.DatabaseConnections.QueryPrompts[btwQuery].Value = mac;
            btFormat.Prompts[btwQuery].Value = mac;
            btFormat.PrintSetup.PrinterName = printer;

            btFormat.Print("标签软件");
            btFormat.PrintSetup.Cache.FlushInterval = CacheFlushInterval.PerSession;
            btFormat.Close(SaveOptions.DoNotSaveChanges);
            bt.Stop();

            //});           
        }

        #endregion

        private void FormYcdMac_Load(object sender, EventArgs e)
        {
            //加载btw的内容
            _printerName = AppSetting.GetValue("PrinterName");
            _objName = AppSetting.GetValue("ObjName");
            _btwPath = AppSetting.GetValue("BtwPath");

            if (string.IsNullOrEmpty(_printerName) || string.IsNullOrEmpty(_objName) || string.IsNullOrEmpty(_btwPath))
            {
                MessageBox.Show("参数配置错误");
                Close();
            }
        }
    }
}
